package com.runvp.rest.app;

import com.alibaba.fastjson.JSONObject;
import com.runvp.common.annotation.Log;
import com.runvp.common.constant.ConstantRedisKey;
import com.runvp.common.core.domain.AjaxResult;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.enums.BusinessType;
import com.runvp.common.enums.NettyCmd;
import com.runvp.common.util.OrderNoUtils;
import com.runvp.common.utils.validtion.CheckException;
import com.runvp.handler.SendCmdHandler;
import com.runvp.service.app.AppClientService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/app/client")
public class ClientController {


    @Autowired
    private RedisCache redisUtil;

    @Autowired
    private AppClientService appClientService;


    /**
     * 设备端口查询
     */
    @Log(title = "设备端口查询", businessType = BusinessType.OTHER)
    @GetMapping("/deviceGoods/{sn}")
    public AjaxResult deviceGoods(@PathVariable("sn") String sn) {
        log.info("deviceGoods:::sn: {}", sn);
        return AjaxResult.success(appClientService.deviceGoods(sn));
    }

    /**
     * 发送指令
     */
    @Log(title = "发送指令", businessType = BusinessType.OTHER)
    @GetMapping("/{cmd}")
    public AjaxResult executeCmd(@PathVariable("cmd") String cmd, String baseSn, String param) {
        String orderNo = OrderNoUtils.getOrderNo();
        log.info("client:::baseSn:{},param:{},orderNo:{}", baseSn, param, orderNo);
        CheckException.strEmptyThrowException(baseSn, "设备SN号为空");
        String body = param + orderNo;
        boolean result = false;
        if(NettyCmd.OUT.getCode().equals(cmd)){
            result =  new SendCmdHandler(redisUtil).sendOutCmd(orderNo, orderNo, baseSn, body);
        }
        if (result) {
            String msg = "订单【" + orderNo + "】出液指令发成功";
            return AjaxResult.success(msg, orderNo);
        }
        String errorMsg = "订单【" + orderNo + "】出液指令发失败或超时";
        log.error(errorMsg);
        return AjaxResult.error(errorMsg);
    }

    /**
     * 查询订单
     */
    @Log(title = "订单查询", businessType = BusinessType.OTHER)
    @GetMapping("/queryOrder/{orderNo}")
    public AjaxResult queryOrder(@PathVariable("orderNo") String orderNo) {
        log.info("client:::orderNo: {}", orderNo);
        String res = redisUtil.getCacheObject(ConstantRedisKey.ORDER + orderNo);
        if (StringUtils.isBlank(res)) {
            return AjaxResult.error("未查到相关信息");
        }
        return AjaxResult.success(JSONObject.parseObject(res));
    }
}
